<template>
  <el-dialog
    v-model="visible"
    title="工单详情"
    width="1100px"
    :close-on-click-modal="false"
  >
    <div class="detail-content" v-loading="loading">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-heading">基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单ID">{{
            ticket.ticket_id || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="工单类型">{{
            getTicketTypeName() || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="责任人">{{
            ticket.assignee_name || ticket.responsible_person || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{
            ticket.assignee_department || ticket.responsible_department || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag
              :type="
                ticket.priority === 'critical'
                  ? 'danger'
                  : ticket.priority === 'high'
                  ? 'warning'
                  : ticket.priority === 'medium'
                  ? 'info'
                  : 'success'
              "
            >
              {{ ticket.priority_name || ticket.priority || "-" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag
              :type="
                ticket.ticket_status === 'pending_review'
                  ? 'warning'
                  : ticket.ticket_status === 'approved'
                  ? 'success'
                  : ticket.ticket_status === 'rejected'
                  ? 'danger'
                  : ticket.ticket_status === 'processing'
                  ? 'info'
                  : ticket.ticket_status === 'completed'
                  ? 'success'
                  : ticket.ticket_status === 'closed'
                  ? 'info'
                  : 'info'
              "
            >
              {{ ticket.ticket_status_name || ticket.ticket_status || "-" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            formatTime(ticket.created_time)
          }}</el-descriptions-item>
          <el-descriptions-item label="聚合告警"
            >{{ ticket.alert_count || 0 }} 条</el-descriptions-item
          >
        </el-descriptions>
      </div>

      <!-- 关联告警列表 -->
      <div class="detail-section">
        <h3 class="section-heading">关联告警列表</h3>
        <DynamicTable
          :data="alertsList"
          :columns="alertsColumns"
          :loading="alertsLoading"
          :show-pagination="false"
          border
        >
          <template #risk_level="{ row }">
            <el-tag
              :type="
                row.risk_level === 'high' || row.risk_level === 'critical'
                  ? 'danger'
                  : row.risk_level === 'medium'
                  ? 'warning'
                  : 'info'
              "
              size="small"
            >
              {{ row.risk_level_name || row.risk_level || "-" }}
            </el-tag>
          </template>
        </DynamicTable>
      </div>

      <!-- 审核历史 -->
      <div class="detail-section">
        <h3 class="section-heading">审核历史</h3>
        <DynamicTable
          :data="reviewHistory"
          :columns="reviewHistoryColumns"
          :loading="reviewHistoryLoading"
          :show-pagination="false"
          border
        >
          <template #status="{ row }">
            <el-tag
              :type="
                row.new_status === 'approved'
                  ? 'success'
                  : row.new_status === 'rejected'
                  ? 'danger'
                  : 'info'
              "
              size="small"
            >
              {{ row.new_status_name || row.new_status || "-" }}
            </el-tag>
          </template>
        </DynamicTable>
      </div>

      <!-- 推送日志 -->
      <div class="detail-section">
        <h3 class="section-heading">推送日志</h3>
        <DynamicTable
          :data="pushLogs"
          :columns="pushLogsColumns"
          :loading="pushLogsLoading"
          :show-pagination="false"
          border
        >
          <template #push_status="{ row }">
            <el-tag
              :type="row.push_status === 'success' ? 'success' : 'danger'"
              size="small"
            >
              {{
                row.push_status_name ||
                (row.push_status === "success" ? "成功" : "失败")
              }}
            </el-tag>
          </template>
        </DynamicTable>
      </div>

      <!-- 处理进度 -->
      <div class="detail-section" v-if="hasProgressInfo">
        <h3 class="section-heading">处理进度</h3>
        <div class="progress-records">
          <div class="record-item" v-if="ticket.resolved_time">
            <div class="record-header">
              <span class="record-time">{{
                formatTime(ticket.resolved_time)
              }}</span>
              <span class="record-separator">|</span>
              <span class="record-person"
                >责任人-{{
                  ticket.assignee_name || ticket.responsible_person || "-"
                }}</span
              >
              <span class="record-separator">|</span>
              <el-tag type="success" size="small">处理完成</el-tag>
            </div>
            <div class="record-content" v-if="ticket.oa_resolution_note">
              <div class="record-label">处理结果:</div>
              <div class="record-value">{{ ticket.oa_resolution_note }}</div>
            </div>
            <div class="record-content" v-if="ticket.resolution_time_hours">
              <div class="record-label">处理时长:</div>
              <div class="record-value">
                {{ ticket.resolution_time_hours.toFixed(2) }} 小时
              </div>
            </div>
          </div>
          <div class="record-item" v-if="ticket.first_response_time">
            <div class="record-header">
              <span class="record-time">{{
                formatTime(ticket.first_response_time)
              }}</span>
              <span class="record-separator">|</span>
              <span class="record-person"
                >责任人-{{
                  ticket.assignee_name || ticket.responsible_person || "-"
                }}</span
              >
              <span class="record-separator">|</span>
              <el-tag type="info" size="small">开始处理</el-tag>
            </div>
            <div class="record-content" v-if="ticket.response_time_hours">
              <div class="record-label">响应时长:</div>
              <div class="record-value">
                {{ ticket.response_time_hours.toFixed(2) }} 小时
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 工单描述 -->
      <div class="detail-section" v-if="ticketDescription">
        <h3 class="section-heading">工单描述</h3>
        <div class="description-content">
          {{ ticketDescription }}
        </div>
      </div>

      <!-- 详细信息 -->
      <div class="detail-section" v-if="ticket.detail">
        <h3 class="section-heading">详细信息</h3>
        <div class="description-content">
          {{ ticket.detail }}
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { TableColumn } from "@/components/DynamicTable/types";
import {
  getTicketAlerts,
  getTicketReviewHistory,
  getTicketPushLogs,
} from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  ticket: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "refresh-list"): void;
  (e: "refresh-stats"): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const loading = ref(false);

// 关联告警列表
const alertsList = ref<any[]>([]);
const alertsLoading = ref(false);

// 审核历史
const reviewHistory = ref<any[]>([]);
const reviewHistoryLoading = ref(false);

// 推送日志
const pushLogs = ref<any[]>([]);
const pushLogsLoading = ref(false);

// 关联告警表格列配置
const alertsColumns: TableColumn[] = [
  {
    label: "告警ID",
    prop: "alert_id",
    minWidth: 150,
    formatter: (row) => {
      return row.alert_id || "-";
    },
  },
  {
    label: "场景类型",
    prop: "scene_type_name",
    minWidth: 120,
    formatter: (row) => {
      return row.scene_type_name || row.scene_type || "-";
    },
  },
  {
    label: "资产IP",
    prop: "asset_ip",
    minWidth: 120,
    formatter: (row) => {
      if (row.asset_port) {
        return `${row.asset_ip || "-"}:${row.asset_port}`;
      }
      return row.asset_ip || "-";
    },
  },
  {
    label: "风险等级",
    prop: "risk_level",
    minWidth: 100,
    slot: "risk_level",
  },
  {
    label: "检测时间",
    prop: "detected_time",
    minWidth: 160,
    formatter: (row) => {
      return formatTime(row.detected_time);
    },
  },
];

// 审核历史表格列配置
const reviewHistoryColumns: TableColumn[] = [
  {
    label: "审核时间",
    prop: "review_time",
    minWidth: 160,
    formatter: (row) => {
      return formatTime(row.review_time);
    },
  },
  {
    label: "审核人",
    prop: "reviewer_name",
    minWidth: 120,
    formatter: (row) => {
      return row.reviewer_name || "-";
    },
  },
  {
    label: "状态变更",
    prop: "status_change",
    minWidth: 150,
    formatter: (row) => {
      if (row.old_status_name && row.new_status_name) {
        return `${row.old_status_name} → ${row.new_status_name}`;
      }
      return row.new_status_name || row.new_status || "-";
    },
  },
  {
    label: "审核状态",
    prop: "new_status",
    minWidth: 100,
    slot: "status",
  },
  {
    label: "审核意见",
    prop: "review_comment",
    minWidth: 200,
    showOverflowTooltip: true,
    formatter: (row) => {
      return row.review_comment || "-";
    },
  },
];

// 推送日志表格列配置
const pushLogsColumns: TableColumn[] = [
  {
    label: "推送时间",
    prop: "push_time",
    minWidth: 160,
    formatter: (row) => {
      return formatTime(row.push_time);
    },
  },
  {
    label: "推送状态",
    prop: "push_status",
    minWidth: 100,
    slot: "push_status",
  },
  {
    label: "OA工单ID",
    prop: "oa_ticket_id",
    minWidth: 150,
    formatter: (row) => {
      return row.oa_ticket_id || "-";
    },
  },
  {
    label: "推送内容",
    prop: "push_content",
    minWidth: 200,
    showOverflowTooltip: true,
    formatter: (row) => {
      return row.push_content || "-";
    },
  },
  {
    label: "错误信息",
    prop: "error_message",
    minWidth: 200,
    showOverflowTooltip: true,
    formatter: (row) => {
      return row.error_message || "-";
    },
  },
];

// 是否有处理进度信息
const hasProgressInfo = computed(() => {
  return (
    props.ticket?.resolved_time ||
    props.ticket?.first_response_time ||
    props.ticket?.processing_progress !== undefined ||
    props.ticket?.processing_notes
  );
});

// 工单描述
const ticketDescription = computed(() => {
  return props.ticket?.ticket_description || props.ticket?.description || "";
});

// 获取工单类型名称
const getTicketTypeName = () => {
  if (props.ticket?.ticket_type_name) {
    return props.ticket.ticket_type_name;
  }
  // 从描述中提取场景类型
  if (props.ticket?.ticket_description) {
    const match = props.ticket.ticket_description.match(/场景类型:\s*([^\n]+)/);
    if (match) {
      return match[1].trim();
    }
  }
  return props.ticket?.ticket_type || "-";
};

// 格式化时间
const formatTime = (time: string | null | undefined): string => {
  if (!time) return "-";
  return time.replace("T", " ").substring(0, 19);
};

// 获取关联告警
const fetchAlerts = async () => {
  if (!props.ticket?.ticket_id) return;

  alertsLoading.value = true;
  try {
    const result = await getTicketAlerts({
      ticket_id: props.ticket.ticket_id,
    });
    if (result?.data) {
      alertsList.value = result.data.alerts || [];
    }
  } catch (error: any) {
    console.error("获取关联告警失败:", error);
    // 不显示错误提示，静默失败
  } finally {
    alertsLoading.value = false;
  }
};

// 获取审核历史
const fetchReviewHistory = async () => {
  if (!props.ticket?.ticket_id) return;

  reviewHistoryLoading.value = true;
  try {
    const result = await getTicketReviewHistory({
      ticket_id: props.ticket.ticket_id,
    });
    if (result?.data) {
      reviewHistory.value = Array.isArray(result.data) ? result.data : [];
    }
  } catch (error: any) {
    console.error("获取审核历史失败:", error);
    // 不显示错误提示，静默失败
  } finally {
    reviewHistoryLoading.value = false;
  }
};

// 获取推送日志
const fetchPushLogs = async () => {
  if (!props.ticket?.ticket_id) return;

  pushLogsLoading.value = true;
  try {
    const result = await getTicketPushLogs({
      ticket_id: props.ticket.ticket_id,
    });
    if (result?.data) {
      pushLogs.value = Array.isArray(result.data) ? result.data : [];
    }
  } catch (error: any) {
    console.error("获取推送日志失败:", error);
    // 不显示错误提示，静默失败
  } finally {
    pushLogsLoading.value = false;
  }
};

// 加载所有数据
const loadAllData = async () => {
  if (!props.ticket?.ticket_id) return;

  // 并行加载所有数据
  await Promise.all([fetchAlerts(), fetchReviewHistory(), fetchPushLogs()]);
};

// 监听弹窗打开状态
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && props.ticket?.ticket_id) {
      // 重置数据
      alertsList.value = [];
      reviewHistory.value = [];
      pushLogs.value = [];
      // 加载数据
      loadAllData();
    }
  },
  { immediate: true }
);

// 监听工单ID变化
watch(
  () => props.ticket?.ticket_id,
  (newId) => {
    if (newId && props.modelValue) {
      loadAllData();
    }
  }
);

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.detail-content {
  max-height: 680px;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-heading {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: #222;
  display: flex;
  align-items: center;
  gap: 8px;
}

.description-content {
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
  line-height: 1.6;
  color: #666;
  white-space: pre-wrap;
  word-break: break-word;
}

// 审核记录、推送记录、处理进度
.review-record,
.push-record,
.progress-records {
  .record-item {
    padding: 12px;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }

    .record-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      flex-wrap: wrap;

      .record-time {
        color: #666;
        font-size: 14px;
      }

      .record-separator {
        color: #999;
      }

      .record-person {
        color: #333;
        font-weight: 500;
      }
    }

    .record-content {
      margin-top: 8px;
      padding-left: 20px;

      .record-label {
        color: #999;
        font-size: 13px;
        margin-bottom: 4px;
      }

      .record-value {
        color: #666;
        line-height: 1.6;
        word-break: break-word;

        &.error-text {
          color: #f56c6c;
        }
      }
    }
  }
}
</style>
